from django.shortcuts import render
from django.http import HttpResponse,JsonResponse
from .. models import Users
import time,os

# Create your views here.
# 后台首页
def index(request):
	
	return render(request,'myadmin/index.html')

# 后台登录页
def login(request):

	return render(request,'myadmin/login.html')

# 执行登录
def dologin(request):
    # 判断验证码是否正确
	# if request.session['verifycode'].lower() != request.POST['vcode'].lower():
		# return HttpResponse('<script>alert("验证码错误");location.href="/admin/login"</script>')
	# 获取用户是否存在
	# try:
	ob = Users.objects.get(name=request.POST['username'])

    # 判断是否为管理员
	if ob.state == '0':
		from django.contrib.auth.hashers import check_password
        # 验证密码
		res = check_password(request.POST['password'],ob.password)
        # 判断密码是否正确
		if res:
            # 登录成功,用户信息.,记录到session,跳转地址
			request.session['AdminLogin'] = {'uid':ob.id,'name':ob.name,'pic':ob.pic}
			return HttpResponse('<script>alert("登录成功");location.href="/admin/"</script>')
		else:
			return HttpResponse('<script>alert("密码不对");location.href="/admin/"</script>')
            # 密码错误
			# raise
	else:
		return HttpResponse('<script>alert("不是管理员");location.href="/admin/"</script>')

	        # 不是管理员
			# raise
	# except:
	# 	return HttpResponse('<script>alert("用户不存在");location.href="/admin/"</script>')

	    # 用户不存在
		# pass    
	# return HttpResponse('<script>alert("用户名或密码不正确");location.href="/admin/login"</script>')

# 退出登录
def logout(request):

	# 清除session登录信息
	request.session['AdminLogin'] = {}

	return HttpResponse('<script>location.href="/admin/login"</script>')



# 会员管理
def userindex(request):
	# 数据分页 
	from django.core.paginator import Paginator

	types = request.GET.get('type',None)
	# 判断是否有用户名的查询条件
	if types == 'name':
		ob = Users.objects.filter(name__contains=request.GET.get('keywords',''))
	# 是否有性别查询
	elif types == 'sex':
	    # 转换关键字
		if request.GET.get('keywords','') == '男':
			ob = Users.objects.filter(sex='1').order_by('id')
		elif request.GET.get('keywords','') == '女':
			ob = Users.objects.filter(sex='0').order_by('id')
		else:
			ob = Users.objects.filter().order_by('id')

	# 是否有状态查询
	elif types == 'status':
	    # 转换关键字
		if request.GET.get('keywords','') == '会员':
			ob = Users.objects.filter(status=1).order_by('id')
		elif request.GET.get('keywords','') == '禁用':
			ob = Users.objects.filter(status=2).order_by('id')
		elif request.GET.get('keywords','') == '管理员':
			ob = Users.objects.filter(status=0).order_by('id')
		else:
			ob = Users.objects.filter().order_by('id')
	else:
	    # 按照查询条件进行查询
		ob = Users.objects.filter().order_by('id')

     # 实例化分页类
	paginator = Paginator(ob,5)

	# 获取当前页码
	p = int(request.GET.get('p',1))

	# 获取分页数据对象
	userlist= paginator.page(p)

	# 分配数据

	context = {'users':userlist,'p':p}
	return render(request,'myadmin/user/index.html',context)

# 会员添加
def useradd(request):
	
	return render(request,'myadmin/user/add.html')
# 添加处理
def admininsert(request):
	from django.contrib.auth.hashers import make_password
	try:
		ob = Users()
		ob.name = request.POST.get('username')
		ob.password = make_password(request.POST['password'],None,'pbkdf2_sha256')
		ob.age = request.POST.get('age')
		ob.sex = request.POST.get('sex')
		ob.phone = request.POST.get('phone')
		ob.state = request.POST.get('state')
		ob.address = request.POST.get('address')
		if request.FILES.get('pic',None):
			ob.pic = upload(request)
		ob.save()
	# return HttpResponse('1')
		return HttpResponse('<script>alert("添加成功");location.href="/admin/userindex"</script>')
	except:
		return HttpResponse('<script>alert("添加失败");location.href="/admin/useradd"</script>')


# 删除
def userdel(request,uid):
	# return HttpResponse('1')
	ob = Users.objects.get(id=uid)
	if str(ob.pic) != '/static/public/pics/user.jpg':

		os.remove('.'+str(ob.pic))

	ob.delete()
	
	return HttpResponse('<script>alert("删除成功");location.href="/admin/userindex"</script>')
# 修改
def useredit(request,uid):
	ob = Users.objects.get(id=uid)
	
	return render(request,'myadmin/user/edit.html',{'uinfo':ob})

# 修改处理
def userupdate(request):
	
	try:
		ob = Users.objects.get(id=request.POST['uid'])
		ob.name = request.POST.get('username')
		if request.POST['password']:
			from django.contrib.auth.hashers import make_password

			ob.password = make_password(request.POST['password'],None,'pbkdf2_sha256')
		
		ob.age = request.POST['age']
		ob.sex = request.POST['sex']
		ob.phone = request.POST['phone']
		ob.state = request.POST['state']
		ob.address = request.POST['address']
		ob.pic = upload(request)
		print('ob.pic',ob.pic)

		myfile = request.FILES.get('pic',None)
		if myfile:
			if ob.pic != './static/public/pics/user.jpg':
				os.remove('.'+ob.pic)
			ob.pic = upload(request)

		ob.save()
	
		return HttpResponse('<script>alert("修改成功");location.href="/admin/userindex"</script>')
	except:
		return HttpResponse('<script>alert("修改失败");location.href="/admin/useredit/'+ob.id+'"</script>')






def upload(request):
	#执行图片的上传
	myfile = request.FILES.get("pic")
	# print(myfile)
	filename = str(time.time())+"."+myfile.name.split('.').pop()

	destination = open("./static/public/pics/"+filename,"wb+")
	for chunk in myfile.chunks():      # 分块写入文件  
	    destination.write(chunk)  
	destination.close()
	# 返回上传的文件名
	return '/static/public/pics/'+filename



# 验证码
def verifycode(request):
	#引入绘图模块
	from PIL import Image, ImageDraw, ImageFont
	#引入随机函数模块
	import random
	#定义变量，用于画面的背景色、宽、高
	bgcolor = (random.randrange(20, 100), random.randrange(
	    20, 100), 255)
	width = 100
	height = 40
	#创建画面对象
	im = Image.new('RGB', (width, height), bgcolor)
	#创建画笔对象
	draw = ImageDraw.Draw(im)
	#调用画笔的point()函数绘制噪点
	for i in range(0, 100):
		xy = (random.randrange(0, width), random.randrange(0, height))
		fill = (random.randrange(0, 255), 255, random.randrange(0, 255))
		draw.point(xy, fill=fill)
	#定义验证码的备选值
	str1 = 'ABCD123EFGHIJK456LMNOPQRS789TUVWXYZ0'
	# str1 = '123456789'
	#随机选取4个值作为验证码
	rand_str = ''
	for i in range(0, 4):
		rand_str += str1[random.randrange(0, len(str1))]
	#构造字体对象
	font = ImageFont.truetype('NotoSansCJK-Light.ttc', 23)
	# font = ImageFont.load_default().font
	#构造字体颜色
	fontcolor = (255, random.randrange(0, 255), random.randrange(0, 255))
	#绘制4个字
	draw.text((5, 2), rand_str[0], font=font, fill=fontcolor)
	draw.text((25, 2), rand_str[1], font=font, fill=fontcolor)
	draw.text((50, 2), rand_str[2], font=font, fill=fontcolor)
	draw.text((75, 2), rand_str[3], font=font, fill=fontcolor)
	#释放画笔
	del draw
	#存入session，用于做进一步验证
	request.session['verifycode'] = rand_str
	#内存文件操作
	import io
	buf = io.BytesIO()
	#将图片保存在内存中，文件类型为png
	im.save(buf, 'png')
	#将内存中的图片数据返回给客户端，MIME类型为图片png
	return HttpResponse(buf.getvalue(), 'image/png')
